// pages/member/course/CourseDetail/CourseDetail.js
import Dialog from "../../../../dist/dialog/dialog";
import polyvLive from "../../../../utils/polyvlive.js";
var CryptoJS = require("../../../../utils/CryptoJS.js");
var yz_pay = require('../../../../mycomponent/yz_pay/yz_pay');
var app = getApp();
Component({
  behaviors: [yz_pay],
  properties: {
    // 属性值可以在组件使用时指定
    prop_goods_info: {
      type: Object, //父组件的商品详情数据
      value: {},
    },
    goodsId: {
      type: Number,
    },
    goodsType: {
      type: String,
    },
    mark: {
      type: String,
    },
    mark_id: {
      type: String,
    },
    ipnonexbol: {
      type: null,
    },
    is_open: {
      type: null,
    },
  },
  observers: {
    is_open: function (num) {
      this.setData({
        questionnaire_is_open: num == "close" ? false : "",
      });
    },
    prop_goods_info:function(obj){
      if(obj){
        console.log(obj,"obj");
        if(obj.get_goods.is_order_detail_comment_show == 1){
          this.data.navList= [
            {id:'list0',name:obj.plugin.lang.course_name+'目录'},
            {id:'list1',name:obj.plugin.lang.course_name+'简介'},
            {id:'list2',name:'评论'}     
          ]
          this.setData({navList:this.data.navList});
        }
      }
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    course_name:"课程",
    imagUrl: app.globalData.imgPath,
    second_top:0,
    three_top:0,
    iPnoneBottomBol: false,
    is_try:0,
    watch_type:0,
    buy_course:0,
    total_page:1,
    page:1,
    video_courses:[],

    has_many_dig_chapter_nums:0,
    has_many_chapter_nums:0,
    is_favorite:0,
    showSahre:false,
    popupModeshow:false,
    navList: [
    //   {
    //   id: "list0",
    //   name: "课程目录"
    // },
    // {
    //   id: "list1",
    //   name: "课程简介"
    // },
    // {
    //   id: "list2",
    //   name: "评论"
    // }
  ],

    navIdx: 0,
    anchorArray:null,

    is_try_time: null,
    is_questionnaire_time: null,
    // 问卷调查
    questionnaire_is_open: false,
    language: "",
    goods_id: "",
    is_show: true,
    is_vshow: false,
    isVideo: true,
    isLook: true,
    is_update: false,
    is_buy: false,
    showPopup: false,
    rewardMoneyBtn: false,
    actionSheetShow: false,
    rewardBtnShow: false,
    // 打赏金额
    rewardMoney: "",
    goodTit: "",
    goodPrice: "",
    chapterNum: "",
    teacherImg: "",
    teacherName: "",
    goodsContent: "",
    chapterList: [],
    article_content: "",
    courseShare: {},
    courseData: {},
    codeUrl: "",
    vedioSrc: "",
    coverImg: "",
    active: 1,
    // 章节id
    chapter_id: "",
    // 课程id
    courseId: "",
    pushGoodList: [],
    actionSheetItems: [],
    isLoding: false,
    activeNames: 1,
    //章节列表
    chapterdigList: [],
    // 价格权限
    vip_level_status: {},
    islive: false,
    video_err: false,
    is_playLive: false,
    live: false,
    videoErr: true,
    // islive:false,
    ios_virtual_pay: false,

    point_goods: "",
    integral: "积分",
    show1: false,
    chapter_content_height:0,

    posterShow: false,
    styleSetOptions: {}, //后台基础设置-样式设置
    countDownTime: null,
    timeData: {},
    iscCountDownFinish: false, //课程有效期是否到了
    HasBuyPermissions: false, //是否有购买权限，true则不可以下单

    videoEventDom: null,
    viewingDuration: 0,//已观看时长
    active_tab:0,
    goods_plugin: null,
    supplierListShow:false,
  },

  lifetimes: {
    attached(e) {
      let language = wx.getStorageSync("langIndex");
      this.setData({
        course_name:this.data.prop_goods_info.plugin.lang.course_name,
        language: language.en,
        is_favorite:this.data.prop_goods_info.is_favorite.status==1?true:false,
        goods_id: this.data.goodsId,
      });
      this.getiPnoneBottom();
      wx.setNavigationBarTitle({
        title: `${this.data.course_name}详情`,
      })
   

      // this.getQrCode()
      this._getData();
      this.footSet();

      try {
        let yz_basic_info = wx.getStorageSync("yz_basic_info");
        this.setData({
          shopName: yz_basic_info.home.mailInfo.name,
          ios_virtual_pay: yz_basic_info.globalParameter.ios_virtual_pay
        });
      } catch (err) {
        console.log(err);
      }

      if (this.data.prop_goods_info.plugin && this.data.prop_goods_info.plugin.point_goods) {
        this.setData({
          point_goods: this.data.prop_goods_info.plugin.point_goods,
        });
      }
      wx.setStorageSync("GoddsShareImg", this.data.prop_goods_info.get_goods.thumb);
      const integral = wx.getStorageSync("integral");
      if (integral) {
        this.setData({
          integral: integral,
        });
      }

    },
    detached() {
      this.data.is_try_time = null;
      this.data.is_questionnaire_time = null;
      clearTimeout(this.data.is_try_time);
      clearTimeout(this.data.is_questionnaire_time);
      // 在组件实例被从页面节点树移除时执行
    },
  },
  pageLifetimes: {
    hide: function () {
      this.data.is_try_time = null;
      this.data.is_questionnaire_time = null;
      clearTimeout(this.data.is_try_time);
      clearTimeout(this.data.is_questionnaire_time);
    },
  },

  methods: {
    initTabsData(){
      // 页面被展示
      let query = wx.createSelectorQuery().in(this);
      let heightArr = [];
      query.selectAll('.navListView').boundingClientRect((react) => {
        console.log(react,"react===");
        react.forEach((res) => {
          heightArr.push(res.top)
        })
        this.setData({
          anchorArray: heightArr,
          second_top:react[1].top
        });
        if(react.length==3){
          this.setData({
            three_top:react[2].top
          })
        }
      }).exec(); //导航栏吸顶

    },
    clickScroll(e) {
      let navIdx = e.target.dataset.idx;
      wx.pageScrollTo({scrollTop:this.data.anchorArray[e.target.dataset.idx]-60,duration: 300,});
      this.setData({navIdx});
    },
    setShare(){
      this.setData({
        showSahre: !this.data.showSahre
      });
    },
    //收藏操作
    onFavorite(e) {
      this.data.favorite ? this.removeFavorite() : this.addFavorite();
    },
    //移除收藏
    removeFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.destroy");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: false,
            });
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 3000,
            });
          } // else {
          //}
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //添加收藏
    addFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.store");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: true,
            });
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 3000,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    change_tab(e){
      this.setData({active_tab:e.detail.index})
    },
    handleContact(e){
      let _url = e.currentTarget.dataset.url;
      if(_url){
        wx.navigateTo({
          url: _url,
          fail:function(err){
            app.tips('客服路径错误');
          }
        });
      }
    },
    tapkefu() {
      this.setData({
        show1: true,
      });
    },
    callPhone() {
      wx.makePhoneCall({
        phoneNumber: this.data.service_mobile,
      });
    },
    closePop() {
      this.setData({
        show1: false,
      });
    },
    changeLoading() {
      this.setData({
        isLoding: true,
      });
    },
    setPosterShow() {
      this.setData({
        posterShow: !this.data.posterShow
      });
    },
    videoErr() {
      wx.showToast({
        title: "视频加载出错了！",
        icon: "none",
        duration: 2000,
      });
      this.setData({
        videoErr: false,
        // is_vshow:false,
      });
    },
    getQrCode() {
      var that = this;
      app._getNetWork({
        url: app.getNetAddresss("member.member.getArticleQr"),
        success: function (res) {
          if (res.data.result == 1 && !app._isTextEmpty(res.data.data)) {
            let _data = res.data.data;
            that.setData({
              codeUrl: _data,
            });
          } else {
            console.error(res);
          }
        },
        fail: function (res) {
          console.error(res);
        },
      });
    },
    secret(string, code, operation) {
      code = CryptoJS.MD5(code).toString();
      var iv = CryptoJS.enc.Utf8.parse(code.substring(0, 16));
      var key = CryptoJS.enc.Utf8.parse(code.substring(16));
      if (operation) {
        return CryptoJS.AES.decrypt(string, key, {
          iv: iv,
          padding: CryptoJS.pad.Pkcs7
        }).toString(CryptoJS.enc.Utf8);
      }
      return CryptoJS.AES.encrypt(string, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }).toString();
    },
    // 点击直播请求
    addzhibo() {
      var that = this;
      app._getNetWork({
        url: app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-live-info"),
        data: {
          goods_id: that.data.goods_id,
        },
        success: function (res) {
          if (res.data.result == 1) {
            if (that.data.islive == true) {
              wx.showToast({
                title: "正在直播",
                icon: "none",
                duration: 1000,
              });
              return;
            }
            let info = JSON.parse(that.secret(res.data.data, "zoQUA@257ggflNmMppKzcU7QgYyp!tU&h54VNN3u!PAU$8FxBW", true));
            that.is_onlive(info.userId, info.channelId);
            that.setData({
              islive: true,
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 1000,
            });
            that.setData({
              is_update: true,
              is_buy: true,
            });
          }
        },
        fail: function (res) {
          console.error(res);
        },
      });
    },
    // 唤起直播
    is_onlive(liveUid, liveVid) {
      wx.showLoading({
        title: "加载直播中",
        icon: "none",
      });
      const liveVideoContext = wx.createLivePlayerContext("polyvLiveVideo");
      this.setData({
        islive: true,
      });
      polyvLive.getVideo({
        uid: liveUid,
        vid: liveVid,
        videoContext: liveVideoContext,
        success: (videoInfo) => {
          // set video src and poster
          this.setPlayerSrc(videoInfo);
        },
        error: (res) => {
          console.log(res.error);
        },
        onStartLive: () => {
          console.log("start live");
          wx.hideLoading();
          // set latest video src
          this.setNewPlayerSrc();
        },
        onApiStatus: (status) => {
          console.log(status);
          if (status == "end") {
            this.setData({
              is_playLive: false,
              islive: false,
              videoErr: true,
              is_vshow: true,
            });
            wx.hideLoading();
            wx.showToast({
              title: "当前无直播",
              icon: "none",
              duration: 1000,
            });
            polyvLive.destroy();
          } else if (status == "live") {
            this.setData({
              is_playLive: true,
            });
          }
        },
      });
    },
    // 直播赋值
    setPlayerSrc(videoInfo) {
      this.setData({
        video: {
          src: videoInfo.src, // 如果播放组件为video,只能用videoInfo.src(m3u8地址)，如果为live-player则用videoInfo.flvSrc
          poster: videoInfo.poster,
        },
        is_bisrc: videoInfo.src,
      });
    },
    setNewPlayerSrc() {
      polyvLive.getNewVideo((videoInfo) => {
        this.setPlayerSrc(videoInfo);
      });
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
      var value = wx.getStorageSync("yz_uid");
      var path = "";
      if (value) {
        path = value;
      }

      let _title = app._isTextEmpty(this.data.courseShare.share_title) ? this.data.goodTit : this.data.courseShare.share_title;

      let _link = "/packageA/detail_v2/detail_v2?id=" + this.data.chapter_id + "&mid=" + path;

      let _imgUrl = app._isTextEmpty(this.data.courseShare.share_thumb) ? this.data.courseData.has_one_goods.thumb : this.data.courseShare.share_thumb;

      let _desc = this.data.courseShare.share_desc;

      return {
        title: _title,
        desc: _desc,
        imageUrl: _imgUrl,
        path: _link
      };
    },
    goSurvey() {
      wx.navigateTo({
        url: "/packageE/questionnaire/questions/questions?goods_id=" + this.data.goods_id + "&tag=video",
      });
    },
    _getData() {
      var that = this;
      // 初次获取数据
      app._getNetWork({
        url: app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-course-goods-detail"),
        data: {
          goods_id: that.data.goods_id,
        },
        success: (res)=> {
          if (res.data.result === 1) {
            let _data = res.data.data;

            if (app._isTextEmpty(_data.has_many_dig_chapter) || _data.has_many_dig_chapter.length == 0) {
              Dialog.alert({
                title: "提示",
                message: `${this.data.course_name}已下架！`,
                context: that,
              }).then(() => {
                // on close
                wx.navigateBack({
                  delta: 1,
                });
              });
              return;
            } else {
              that.setData({
                chapterdigList: _data.has_many_dig_chapter,
              });
            }

            _data.has_one_goods.content = _data.has_one_goods.content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');

            let playCourse = "";
            let playActive = 0;
            let has_many_dig_chapter = _data.has_many_dig_chapter;

            for (let j = 0; j < has_many_dig_chapter.length; j++) {
              if (has_many_dig_chapter[j].has_many_chapter.length > 0 && that.data.chapter_id) {
                for (let i = 0; i < has_many_dig_chapter[j].has_many_chapter.length; i++) {
                  if (has_many_dig_chapter[j].has_many_chapter[i].id === Number(that.data.chapter_id)) {
                    playCourse = has_many_dig_chapter[j].has_many_chapter[i];
                    playActive = i;
                  }
                }
              } else {
                playActive = 0;
                playCourse = has_many_dig_chapter[0].has_many_chapter[0];
              }
            }

            let goodPrice = "";
            if (that.data.point_goods) {
              goodPrice = that.data.point_goods.point;
            } else {
              goodPrice = _data.has_one_goods.price;
            }
            let countDownTime = _data.course_expiration_time?app.getTimeDifference(_data.course_expiration_time):null;
            if(goodPrice == '0.00'){
              that.setData({buy_course:1})
            }else{
              that.setData({buy_course:_data.is_buy})
            }
            let customer_service = this.data?.prop_goods_info?.customer_service || data.shopSet;
            that.setData({
              is_try:_data.is_try,
              course_id:_data.id,
              has_many_dig_chapter_nums:_data.has_many_dig_chapter.length,
              has_many_chapter_nums:_data.course_chapter_num,
              courseData: _data,
              rewardBtnShow: _data.is_reward,
              goodTit: _data.has_one_goods.title,
              goodPrice: goodPrice,
              vip_level_status: _data.has_one_goods.vip_level_status,
              chapterNum: _data.course_chapter_num,
              teacherImg: _data.has_one_lecturer && _data.has_one_lecturer.has_one_member ? _data.has_one_lecturer.has_one_member.avatar : '',
              teacherName: _data.has_one_lecturer && _data.has_one_lecturer.real_name||'',
              goodsContent: _data.has_one_goods.content,
              chapter_id: playCourse && playCourse.id || 0,
              isLook: playCourse && playCourse.is_audition || true,
              courseId: _data.id,
              pushGoodList: _data.pushGoods,
              courseShare: _data.has_one_goods.has_one_share,
              live: _data.live,
              live_title: _data.live_title,
              questionnaire_time: _data.questionnaire_time,
              service_QRcode: customer_service.service_QRcode,
              service_mobile: customer_service.service_mobile,
              shopSet: customer_service,
              plugin_point_name: _data.plugin_point_name ? _data.plugin_point_name : '',
              styleSetOptions: _data.styleSet,
              countDownTime: countDownTime,
              HasBuyPermissions: _data.buyPermissions||false,
              advertising:  _data?.has_one_goods?.has_one_goods_advertising ?? {},
              goods_plugin: _data.plugin
            });

            that.getVideoCourse();
            let sec = _data.questionnaire_time * 1000;
            if (_data.questionnaire_is_open) {
              if (that.data.is_opens == "close") {
                console.log(that.data.is_opens);
              } else {
                that.data.is_questionnaire_time = setTimeout(() => {
                  if (!that.data.is_questionnaire_time) {
                    return;
                  }
                  that.setData({
                    questionnaire_is_open: _data.questionnaire_is_open,
                  });
                }, sec);
              }
            }
            setTimeout(() => {
              that.initTabsData();
            }, 1000);
            switch (_data.watch) {
            case 0:
              // Dialog.alert({
              //   title: '提示',
              //   message: '请升级会员或者购买课程',
              //   context: that
              // }).then(() => {
              //   // on close
              // })
              that.setData({
                is_update: false,
                is_buy: false,
              });
              that.videoInit(playActive, playCourse);
              break;
            case 1:
              // 判断是否免费章节
              // if (playCourse.is_audition == 1) {
                that.setData({
                  is_update: false,
                  is_buy: false,
                  is_show: false,
                  is_vshow: true,
                });
                that.videoInit(playActive, playCourse);
                break;
              // } else if (playCourse.is_audition == 0) {
              //   Dialog.alert({
              //     title: "提示",
              //     message: "请升级会员或者购买课程",
              //     context: that,
              //   }).then(() => {
              //     // on close
              //   });
              //   that.setData({
              //     is_update: true,
              //     is_buy: true,
              //   });
              //   break;
              // } else {
              //   break;
              // }
            case 2:
              that.setData({
                is_update: false,
                is_buy: false,
              });
              that.videoInit(playActive, playCourse);
              break;
            case 3:
            case 4:
              that.setData({
                is_update: false,
                is_buy: false,
              });
              that.videoInit(playActive, playCourse);
              break;
            default:
              break;
            }

            wx.setStorageSync("orderErrReturnUrl", _data.mini_not_permit_link);//无权限购买时，下单弹出框确认按钮跳转路径
          } else {
            wx.showToast({
              title: "视频加载出错",
              icon: "none",
              duration: 1500,
            });
            console.error(res);
          }
      
        },
        fail: function (res) {
          console.error(res);
        },
      });
    },
    videoInit(index, item) {
      // if(!item) return;
      this.setData({
        is_show: false,
        is_vshow: true,
        active: item.id,
      });
      this.viewPermission(item.id, index, item.course_id, item.is_audition);
      this.isMp4(this.data.vedioSrc);
    },
    viewPermissionBtn(e) {

      let dataset = e.currentTarget.dataset;
      let id = dataset.item.id;
      let index = dataset.index;
      let parent_index = dataset.parentindex +1;
      let course_id = dataset.item.course_id;
      let audition = dataset.item.is_audition;
      if(audition||this.data.goodPrice=='0.00'||this.data.buy_course||this.data.is_try){

        wx.navigateTo({
          url: `/mircoApp/videoOnDemand/index/index?chapter_id=${id}&course_id=${course_id}&goods_id=${this.data.goodsId}&index=${parent_index}`,
        })
        return;
      }
      if(this.data.buy_course==0&&audition==0&&this.data.is_try==0){
        this.setData({watch_type:0,active:id})
        this.openBuyDialog();
        return;
      }
      this.viewPermission(id, index, course_id, audition);
    },
    // 根据观看权限
    viewPermission(id, index, course_id, audition) {
      // id, index, address, course_id, audition
      let that = this;
      this.setData({
        is_show: true,
        is_vshow: false,
        islive: false,
      });
      this.setData({
        chapter_id: id,
        active: id,
      });

      let param = {
        goods_id: this.data.goods_id,
        chapter_id: id,
      };
      let url = app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-video-address");
      app._getNetWork({
        url: url,
        data: param,
        success: function (res) {
          if (res.data.result == 1) {
            let _data = res.data.data;
            that.viewType(_data.watch, index, _data.video_address, course_id, id, audition, _data.video_cover_address, _data.is_try, _data.try_time);
          } else {
            console.error(res);
          }
        },
        fail: function (res) {
          console.error(res);
        },
      });
    },
    // 获取手机型号
    getiPnoneBottom() {
      let value = wx.getStorageSync("iPhoneBottom");
      if (value) {
        this.setData({
          iPnoneBottomBol: true,
        });
      }
    },
    viewType(type, index, address, course_id, id, audition, coverSrc, is_try, try_time) {
      this.setData({watch_type:type})
      this.freeTime = -1;
      if (is_try == 1 && type == 1 && audition == 1) {
        console.log("执行1");
        this.setData({
          coverImg: coverSrc,
          is_update: false,
          is_buy: false,
          isLook: true,
          is_vshow: true,
          is_show: false,
        });
        this.videoPlay(index, address, course_id, id, coverSrc);
        return;
      } else if (type != 2 && type != 3 && type != 4 && is_try == 1 && try_time > 0) {
        console.log("执行2");
        this.setData({
          is_update: false,
          is_buy: false,
          isLook: true,
        });
        this.freeTime = try_time;
        this.videoPlay(index, address, course_id, id, coverSrc);
        this.data.videoEventDom = wx.createVideoContext('polyvLiveVideo',this);
        return;
      } else {
        console.log("执行3");
        this.setData({
          vedioSrc: address,
          coverImg: coverSrc,
        });
        this.isMp4(this.data.vedioSrc);
      }
      switch (type) {
      case 0:
        this.setData({
          is_vshow: false,
          is_show: true,
        });
        this.isNoPlay();
        break;
      case 1:
        if (audition == 1) {
          this.setData({
            is_update: false,
            is_buy: false,
            isLook: true,
            is_vshow: true,
            is_show: false,
          });
          this.videoPlay(index, address, course_id, id, coverSrc);
          break;
        } else if (audition == 0) {
          this.isNoPlay();
          break;
        } else {
          break;
        }
      case 2:
        this.setData({
          is_update: false,
          is_buy: false,
          isLook: true,
        });
        this.videoPlay(index, address, course_id, id, coverSrc);
        break;
      case 3:
      case 4:
        this.setData({
          is_update: false,
          is_buy: false,
          isLook: true,
        });
        this.videoPlay(index, address, course_id, id, coverSrc);
        break;
      default:
        break;
      }
    },
    isNoPlay() {
      this.setData({
        is_update: true,
        is_buy: true,
        isLook: false,
      });
      if (!this.data.styleSetOptions.buy_now_button) return;
      this.openBuyDialog();
    },
    openBuyDialog(){
      if(this.data.buy_course){
        return;
      }
      if(this.data.is_try_time) {
        clearTimeout(this.data.is_try_time);
        this.data.is_try_time = null;
      }
      Dialog.alert({
        title: "提示",
        message:this.data.prop_goods_info.plugin?.tip_msg ||  `请升级会员或者购买${this.data.course_name}`,
        context: this,
      }).then(() => {
        // on close
      });
    },


    videoTimeupdate(event){
      if(Number(this.freeTime) > -1 && parseInt(event.detail.currentTime) == this.freeTime) {
        this.setData({
          islive: false,
          is_show: true,
          is_vshow: false
        });
        this.isNoPlay();
      }

      if(Number(this.freeTime) > -1 && event.detail.currentTime > this.freeTime) {
        wx.showToast({
          title: `试看时长为${this.freeTime}秒`,
          icon: "none",
          duration: 1500,
        });
        this.data.videoEventDom.seek(Number(this.freeTime) - 2);
      }
    },
    // 观看视频
    videoPlay(index, src, course_id, id, coverSrc) {
      this.setData({
        is_show: false,
        is_vshow: true,
        active: id,
        vedioSrc: src,
        coverImg: coverSrc,
      });

      // 判断当前路径
      this.isMp4(this.data.vedioSrc);

      app._getNetWork({
        url: app.getNetAddresss("plugin.video-demand.api.video-demand-member.set-watch-history"),
        data: {
          course_id: course_id,
          chapter_id: id,
        },
        success: function (res) {},
      });
    },
    // 判断是否MP4
    isMp4(src) {
      if (src == "") return;
      if (src.endsWith(".mp4") || src.endsWith(".MP4")) {
        this.setData({
          isVideo: true,
          is_show: false,
        });
      } else {
        this.setData({
          isVideo: false,
          is_show: false,
        });
      }
    },
    study() {
      this.setData({
        is_show: false,
        is_vshow: true,
      });
    },
    // 升级会员
    update() {
      if (this.data.ios_virtual_pay) {
        wx.showModal({
          title: "提示",
          content: "十分抱歉，由于相关规定，你暂时无法在这里充值！",
          confirmText: "知道了",
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log(res);
            }
          },
        });
        return false;
      }
      wx.navigateTo({
        url: "/packageA/member/course/CourseMemberUpdate/CourseMemberUpdate?goods_id=" + this.data.goods_id,
      });
    },
    // 立即购买
    buy() {
      if(this.data.HasBuyPermissions){
        wx.showModal({
          title: "提示",
          content: this.data.HasBuyPermissions,
          confirmText: "确定",
          showCancel: false,
          success(res) {},
        });
        return false;
      }
      if (this.data.ios_virtual_pay) {
        wx.showModal({
          title: "提示",
          content: "十分抱歉，由于相关规定，你暂时无法在这里充值！",
          confirmText: "知道了",
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log(res);
            }
          },
        });
        return false;
      }
      //价格权限
      if (this.data.vip_level_status && this.data.vip_level_status.status == 1) {
        wx.showToast({
          title: this.data.vip_level_status.tips,
          icon: "none",
          duration: 1500,
        });
        return false;
      }

      wx.navigateTo({
        url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=-2&total=1&optionsId=&goodsId=" + this.data.goods_id,
      });
    },
    // 跳转至我的课程
    toMyCourse() {
      wx.navigateTo({
        url: "/packageA/member/course/CourseMy/CourseMy",
      });
    },
    toHome(){
      if(this.data.prop_goods_info.get_goods.supplier) {
        return this.setData({supplierListShow: true});
      }
      wx.navigateTo({
        url: "/packageG/index/index",
      });
    },
    copyMidLink(){
      let mid = wx.getStorageSync("yz_uid");
      let url = `${app.data.host}/addons/yun_shop/api.php?i=${app.data.uniacid}&route=plugin.min-app.Frontend.Controllers.page.goods-url&goods_id=${this.data.prop_goods_info.get_goods.id}&mid=${mid}`;
      this.onClipboardData(url);
    },
    onClipboardData(data){
      wx.setClipboardData({
        data: data,
        success(res) {
          wx.showToast({
            icon: 'none',
            title: '复制成功',
            duration: 1000
          });
        },fail(err){
          console.log(err);
        }
      });
    },
    // 推荐商品跳转
    pushGoodGoto(val) {
      let item = val.currentTarget.dataset.item;
      wx.navigateTo({
        url: "/packageA/detail_v2/detail_v2?id=" + item.id,
      });
    },
    // 选择打赏金额
    chooseMoney(e) {
      let money = e.currentTarget.dataset.money;
      this.setData({
        rewardMoney: money,
      });
    },
    moneyInput(e) {
      this.setData({
        rewardMoney: e.detail,
      });
    },
    // 确定打赏
    confirmReward() {
      if (app._isTextEmpty(this.data.rewardMoney)) {
        wx.showToast({
          title: "请输入或选择打赏金额",
          icon: "none",
          duration: 1500,
        });
        return;
      }

      if (this.data.rewardMoney <= 0) {
        wx.showToast({
          title: "打赏金额必须大于0",
          icon: "none",
          duration: 1500,
        });
        return;
      }

      this.getPayData();
    },
    // 获取支付类型参数
    getPayData() {
      var that = this;
      app._getNetWork({
        url: app.getNetAddresss("plugin.video-demand.api.lecturer-reward.pay-type"),
        success: function (res) {
          if (res.data.result === 1) {
            let btnData = res.data.data.buttons;
            that.setData({
              showPopup: false,
              btnData: btnData,
              rewardPayshow: true,
            });
          } else {
            console.error(res);
          }
        },
        fail: function (res) {
          console.error(res);
        },
      });
    },
    // 支付
    payPost(e) {
      this.setData({
        rewardPayshow: false,
      });
      let type, name, btn = null;
      if (e.currentTarget) {
        type = e.currentTarget.dataset.info.value;
        name = e.currentTarget.dataset.info.name;
        btn = e.currentTarget.dataset.info;
      } else {
        type = e.value;
        name = e.name;
        btn = e;
      }
      let dataJson = {
        pay_method: type,
        amount: this.data.rewardMoney,
        pay_name: name,
        goods_id: this.data.goodsId,
        trick_id: this.data.stickid,
        client_type: "2",
      };

      app._getNetWork({
        url: app.getNetAddresss("plugin.video-demand.api.lecturer-reward.run-reward-pay"),
        data: dataJson,
        success: (res) => {
          if (res.data.result === 1) {
            this.handleOtherPay(btn, type, res.data.data);
            this.onClose();
          } else {
            Dialog.alert({
              title: "提示",
              message: res.data.msg,
              context: this,
            }).then(() => {
              // on close
            });
          }
        },
        fail: (res) => {
          console.error(res);
        },
      });
    },
    moneyShow() {
      this.setData({
        showPopup: true,
      });
    },
    openInputReward() {
      this.setData({
        showPopup: false,
        rewardMoneyBtn: true,
      });
    },
    onClose() {
      this.setData({
        showPopup: false,
        rewardMoneyBtn: false,
        actionSheetShow: false,
        questionnaire_is_open: false,
      });
    },
    openActionSheet() {
      this.setData({
        showPopup: false,
        actionSheetShow: true,
      });
    },
    previewImage: function (e) {
      var current = e.target.dataset.src; // 这里获取到的是一张本地的图片
      wx.previewImage({
        current: current, // 需要预览的图片链接列表
        urls: [current], // 当前显示图片的链接
      });
    },
    // 足迹记录
    footSet() {
      if (!this.data.isGoods) {
        return;
      }
      let urlStr = app.getNetAddresss("member.member-history.store");
      urlStr += "&goods_id=" + this.properties.goodsId + "&mark=" + this.properties.mark + "&mark_id=" + this.properties.mark_id;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res);
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    animationEnd({detail:height}){
      this.data.anchorArray[1] =  this.data.anchorArray[1] + height;
      if(this.data.three_top){
        this.data.anchorArray[2] =  this.data.anchorArray[2] + height;
      }
      this.setData({anchorArray:this.data.anchorArray})
    },
    close(event){
      this.data.anchorArray[1] = this.data.second_top;
      if(this.data.three_top){
        this.data.anchorArray[2] = this.data.three_top;
      }
      this.setData({anchorArray:this.data.anchorArray})
    },
    onChange(event) {
      this.setData({
        activeNames: event.detail,
      });
    },
    rewardPayshowClose() {
      this.setData({
        rewardPayshow: false,
      });
    },
    rewardPayCancelBtn() {
      this.setData({
        rewardPayshow: false,
      });
    },
    onChangecountDown(e) {
      this.setData({
        timeData: e.detail,
      });
    },
    countDownFinish(){
      this.setData({
        iscCountDownFinish: true
      });
    },
    // 去加群
    toGroupCode() {
      if(this.data.goods_plugin.group_code.jump_mode === 'home') {
        wx.reLaunch({
          url: '/packageE/groupCode/groupCode',
        });
      }else if(this.data.goods_plugin.group_code.code_mini_url){
        wx.navigateTo({
          url: this.data.goods_plugin.group_code.code_mini_url
        });
      }
    },
    // 广告语跳转
    toAdvertising() {
      wx.navigateTo({
        url: this.data.advertising.min_link
      });
    },
    getVideoCourse(page=1){
      app._getNetWork({
        url:app.getNetAddresss("plugin.video-demand.api.video-course-goods.get-dig-chapter"),
        data:{page,course_id:this.data.course_id},
        success:resdata=>{
          let {result,msg,data} = resdata.data;
          if(result!==1){
            return app.tips(msg);
          }
          this.setData({page:data.current_page,total_page:data.last_page})
          if(page==1){
            this.setData({video_courses:data.data})
          }else{
            let video_courses = this.data.video_courses.concat(data.data);
            this.setData({video_courses})
          } 
          
          let query = wx.createSelectorQuery().in(this);
          query.selectAll('.chapter-content').boundingClientRect((react) => {
            if(this.data.chapter_content_height){
              let h = react[0].height -  this.data.chapter_content_height;
              this.data.anchorArray[1] = this.data.anchorArray[1] +h;
              if(this.data.anchorArray[2]){
                this.data.anchorArray[2]  = this.data.anchorArray[2] +h;
              }
            }
            this.setData({chapter_content_height:react[0].height,anchorArray:this.data.anchorArray})
          }).exec(); //导航栏吸顶
        },
      })
    },
    getMoreData(){
      if(this.data.page>=this.data.total_page){
        return;
      }
      let page = this.data.page + 1;
      this.getVideoCourse(page);
    },
    play_look(){
      wx.navigateTo({
        url: `/mircoApp/videoOnDemand/index/index?chapter_id=${this.data.active}&course_id=${this.data.courseId}&goods_id=${this.data.goodsId}`,
      })
    },
    closeShopList(){
      this.setData({
        supplierListShow:false
      })
    },
  },
});
